

package com.hazelcast.internal.util.collection;

import com.hazelcast.multimap.MultiMap;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static com.hazelcast.internal.util.Preconditions.checkNotNull;

/**
 * Simplistic implementation of MultiMap.
 * It's not thread-safe, concurrent access has to be externally synchronized.
 * <p>
 * It does not allow duplicates: The same value can be associated with the same key once only. Duplicates are
 * eliminated.
 * <p>
 * The name has a prefix Internal- to avoid confusion with {@link MultiMap}
 *
 * @param <K>
 * @param <V>
 */
public class InternalSetMultimap<K, V> {
    private final Map<K, Set<V>> backingMap;

    public InternalSetMultimap() {
        this.backingMap = new HashMap<>();
    }

    /**
     * Associate value to a given key. It has no effect if the value is already associated with the key.
     */
    public void put(K key, V value) {
        checkNotNull(key, "Key cannot be null");
        checkNotNull(value, "Value cannot be null");

        Set<V> values = backingMap.computeIfAbsent(key, x -> new HashSet<>());
        values.add(value);
    }

    /**
     * Return Set of values associated with a given key
     */
    public Set<V> get(K key) {
        checkNotNull(key, "Key cannot be null");
        return backingMap.get(key);
    }

    public Set<Map.Entry<K, Set<V>>> entrySet() {
        return backingMap.entrySet();
    }
}
